package com.houor.device.controller.handler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerContext;

/**
 * ChannelHandlerContext容器
 * 
 * 维护客户端连接
 * 
 * @author Houor
 *
 * @createTime 2017-04-25 15:58
 */
public class ChannelHandlerContextMap {

	private static Logger logger = LoggerFactory.getLogger(ChannelHandlerContextMap.class);

	private static Map<Long, ChannelHandlerContextContainer> ctxMap = new ConcurrentHashMap<Long, ChannelHandlerContextContainer>();

	public static void put(Long controllerId, ChannelHandlerContext channelHandlerContext) {
		logger.debug("Add {} : {} to Map.", controllerId, channelHandlerContext);
		ctxMap.put(controllerId, new ChannelHandlerContextContainer(channelHandlerContext));
	}

	public static ChannelHandlerContext get(Long controllerId) {
		if (ctxMap.get(controllerId) == null) {
			return null;
		} else {
			return ctxMap.get(controllerId).getChannelHandlerContext();
		}
	}

	public static void removeById(Integer controllerId) {
		ctxMap.remove(controllerId);
	}

	public static void remove(ChannelHandlerContext channelHandlerContext) {
		for (Map.Entry<Long, ChannelHandlerContextContainer> entry : ctxMap.entrySet()) {
			if (entry.getValue().getChannelHandlerContext().channel().id() == channelHandlerContext.channel().id()) {
				logger.debug("Remove {} : {} from Map.", entry.getKey(), channelHandlerContext);
				ctxMap.remove(entry.getKey());
			}
		}
	}

}

class ChannelHandlerContextContainer {

	private ChannelHandlerContext channelHandlerContext;

	public ChannelHandlerContextContainer(ChannelHandlerContext channelHandlerContext) {
		this.channelHandlerContext = channelHandlerContext;
	}

	public ChannelHandlerContext getChannelHandlerContext() {
		return channelHandlerContext;
	}

	public void setChannelHandlerContext(ChannelHandlerContext channelHandlerContext) {
		this.channelHandlerContext = channelHandlerContext;
	}

}
